using System;
using System.Threading;
using Cysharp.Threading.Tasks;
using QFramework;
using R3;
using Sirenix.OdinInspector;
using UnityEngine;

public class R3_Example:MonoBehaviour
{
    CancellationTokenSource cts = new CancellationTokenSource();
    
    [Button("开启R3Update测试")]
    public void R3_EveryUpdate()
    {
        Observable.EveryUpdate()
            .Subscribe(_ => Debug.Log("Sub")).AddTo(this);
    }

    [Button("关闭R3Update测试")]
    public void R3_CloseUpdateToken()
    {
        cts?.Cancel();
    }

    [Button("开启R3订阅测试")]
    void R3_Func1()
    {
        Observable.Create<int>(async (observer, ct) =>
        {
            await UniTask.Delay(1000, cancellationToken: ct);
            observer.OnNext(1);
        
            await UniTask.Delay(1000, cancellationToken: ct);
            observer.OnNext(2);
        
            await UniTask.Delay(1000, cancellationToken: ct);
            observer.OnNext(3);
            observer.OnCompleted();
        
        }).Subscribe( 
            onNext: value => Debug.Log($"Received: {value}"),
            onErrorResume: ex => Debug.Log($"Error: {ex.Message}"),
            onCompleted: (result) => Debug.Log($"Completed!:{result.ToString()}"));

        var obs2 = Observable.Create<int>((observer) =>
        {
            observer.OnNext(4);
            observer.OnNext(5);
            observer.OnNext(6);
            observer.OnCompleted();
            
            return Disposable.Empty;
        })
            .Subscribe(onNext: value => { Debug.Log($"Received:{value}"); });

    }
}
